package utils
{
	import flash.filesystem.File;
	
	import model.data.BaseData;
	import model.data.Book;

	public class ParagraphProcessor extends BaseData
	{
		public function ParagraphProcessor()
		{
			load();
		}
		
		private var __words:Array;
		private static const CHOOSE:String = "volba";
		
		override protected function process(data:String):void
		{
			__words = [];		
			var list:Array = data.split("\r\n");
			
			for (var i:int=0; i< list.length;i++)
				if (list[i].indexOf("--") == -1)
					__words.push(list[i]..replace(/ /g,"").toLowerCase());
		}
		
		override protected function get store():File
		{
			return super.store.resolvePath("words.txt");
		}
		

		public function processParagraph(value:String):String
		{
			var rows:Array = value.split("\r");
			var hasTitle:Boolean = isTitle(rows[0]);	
			
			var content:String = "";
			
			for (var i:int=0;i<rows.length;i++)
			{
				var row:String = rows[i];
				
				if (i==0 && hasTitle)
					row = "<i><b>"+row+"</b></i>";
				
				row = handleColon(row);
				
				if ((i==1 && hasTitle) || row.indexOf(CHOOSE.toUpperCase()) != -1)
					content += "\n"
				
				content += " "+row;
			}
			
			content = handleRewards(content);
			
			return content;
		}
		
		private function handleColon(row:String):String
		{
			var index:int = row.indexOf(":");
			
			if (index == -1) return row;
			
			var beforeColon:String = row.substring(0,index).replace(/ /g,"").toLowerCase();
			
			if (beforeColon.indexOf(CHOOSE) == 0) 
				return addBoldToIndex(row,index, "   "+String.fromCharCode(8226));
			
			if (beforeColon.indexOf("[") == -1)
			{
				var m:Array = beforeColon.match(/[0-9]-[0-9]/) || beforeColon.match(/[0-9]\+/) || beforeColon.match(/-[0-9]/) || beforeColon.match(/[0-9]/);
				if (m && m.length)
					return addBoldToIndex(row, index, "  "+String.fromCharCode(8226));	
			}
				
			for (var i:int=0;i< __words.length;i++)
				if (beforeColon.indexOf(__words[i]) != -1)
					return addBoldToIndex(row,index);
			
			return row;
		}
		
		private function addBoldToIndex(value:String, index:int, specialChar:String=null):String
		{
			return "\n"+(specialChar ? specialChar:"")+"<b>"+value.substring(0,index)+"</b>"+value.substring(index);
		}
		
		private function handleRewards(value:String):String
		{
			var match:Array = value.match(/\[.*\]/g);
			
			for (var j:int=0; j<match.length;j++)
				value = value.replace(match[j], '<font color="#ff0000"><i>'+match[j]+'</i></font>');
			
			return value;
		}
		
		private function isTitle(value:String):Boolean
		{
			return value.toUpperCase() == value;
		}
	}
}